package com.yuzhantao.collection.sensorflow.response.coder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.yuzhantao.collection.sensorflow.message.SensorFlowMessage;

@Service
public class SensorFlowCoder {
	protected final static Logger logger = LoggerFactory.getLogger(SensorFlowCoder.class);

	/**
	 * 编码
	 * 
	 * @param sf
	 * @return
	 */
	public String encode(Object sf) {
		String json = JSON.toJSONString(sf);
		StringBuffer sbu = new StringBuffer();
		char[] chars = json.toCharArray();
		for (int i = 0; i < chars.length; i++) {
			if (i != chars.length - 1) {
				sbu.append((int) chars[i]).append(",");
			} else {
				sbu.append((int) chars[i]);
			}
		}
		return sbu.toString();
	}

	/**
	 * 解码消息
	 * 
	 * @param message
	 * @return
	 */
	public SensorFlowMessage decode(String message) {
		try {
			SensorFlowMessage sf = JSON.parseObject(message, SensorFlowMessage.class);
			return sf;
		} catch (Exception e) {}

		String[] ms = message.split(",");
		StringBuffer sb = new StringBuffer();
		try {
			for (int i = 0; i < ms.length; i++) {
				sb.append(this.convertIntToAscii(Integer.valueOf(ms[i])));
			}
			logger.debug("解析消息:" + sb.toString());
			SensorFlowMessage sf = JSON.parseObject(sb.toString(), SensorFlowMessage.class);
			return sf;
		} finally {
			sb.setLength(0);
		}
	}

	private char convertIntToAscii(int a) {
		return (a >= 0 && a <= 255) ? (char) a : '\0';
	}
}
